package com.zara.store.server;

import java.math.BigDecimal;
import java.util.ArrayList;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.zara.store.common.InvoiceItemVO;
import com.zara.store.common.InvoiceVO;
import com.zara.store.common.ProductVO;

public @Stateless class InvoiceBusinessBean implements InvoiceBusiness {

	@PersistenceContext(name="ZARA")
	private EntityManager entityManager;
	
	public ProductVO queryProduct(String barcode) {
		Query query = entityManager.createQuery("FROM Product product WHERE product.barcode = ?");
		query.setParameter(1, barcode);
		try {
			Product product = (Product) query.getSingleResult();
			return product.toVO();
		} catch(NoResultException e) {
			//TODO: log error
		} catch(NonUniqueResultException e) {
			//TODO: log error
		}
		return null;
	}

	@TransactionAttribute (TransactionAttributeType.REQUIRED)
	public InvoiceVO createInvoice(InvoiceVO invoiceVO) {
		//invoice item sanity check
		InvoiceVO invoiceVO2 = null;
		ArrayList<InvoiceItem> items = new ArrayList<InvoiceItem>();
		for(InvoiceItemVO i: invoiceVO.getElements()) {
			int productId = i.getProductId();
			Product p = entityManager.find(Product.class, productId);
			BigDecimal amount = i.getAmount();
			BigDecimal stock = p.getStock();
			if(stock.compareTo(amount) < 0) { //no stock
				if(invoiceVO2 == null)
					invoiceVO2 = new InvoiceVO(0);
				invoiceVO2.addLine(new InvoiceItemVO(productId));
			}
			InvoiceItem item = new InvoiceItem();
			item.setProduct(p);
			item.setAmount(amount);
			item.setPrice(i.getPrice());
			item.setTotal(i.getTotal());
			items.add(item);
		}
		if(invoiceVO2 != null) {
			return invoiceVO2;
		}
		
		InvoiceClient client = new InvoiceClient();
		client.setClientAddress(invoiceVO.getClientAddress());
		client.setClientCUIT(invoiceVO.getClientCUIT());
		client.setClientName(invoiceVO.getClientName());
		client.setClientStatusIVA(invoiceVO.getClientStatusIVA());
		entityManager.persist(client);

		Invoice invoice = new Invoice();
		invoice.setSubTotal(invoiceVO.getSubTotal());
		invoice.setTotal(invoiceVO.getTotal());
		invoice.setTaxIVA(invoiceVO.getTaxIVA());
		invoice.setInvoiceType(invoiceVO.getInvoiceType());
		entityManager.persist(invoice);

		for(InvoiceItem item: items) {
			Product product = item.getProduct();
			BigDecimal newStock = product.getStock().subtract(item.getAmount());
			product.setStock(newStock);
			entityManager.merge(product);
			item.setInvoice(invoice);
			entityManager.persist(item);
		}
		return new InvoiceVO(invoice.getId());
	}

}
